/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.dictionary.impl.typed;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.service.MetaService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.dd.DicInfoCache;
import com.je.meta.model.dd.DicInfoVo;
import com.je.meta.rpc.dictionary.CustomBeanInvokeRpcService;
import com.je.meta.service.dictionary.AbstractMetaDictionaryTreeServiceImpl;
import com.je.meta.service.dictionary.MetaDictionaryTreeService;
import com.je.servicecomb.RpcSchemaFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import static com.je.servicecomb.JECloud.PRODUCT_CORE_META;

@Service("customDictionaryTreeService")
public class CustomDictionaryTreeServiceImpl extends AbstractMetaDictionaryTreeServiceImpl implements MetaDictionaryTreeService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private DicInfoCache dicInfoCache;

    @Override
    public List<JSONTreeNode> loadAsynTree(JSONObject obj, String product, boolean en, boolean onlyItem) {
        String ddCode = obj.getString("ddCode");
        //查找字典主表记录
        DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
        if (dictionary == null) {
            dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode));
        }
        if (dictionary == null) {
            throw new PlatformException("未找到数据字典：" + ddCode + "!", PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR, new Object[]{ddCode});
        }
        //字典类型，本方法支持[外部树形字典，列表字典，树形字典]
        String ddType = dictionary.getStr("DICTIONARY_DDTYPE");
        throw new PlatformException("不支持的异步字典类型：" + ddType + "!", PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR, new Object[]{ddType});
    }

    @Override
    public List<JSONTreeNode> loadSyncTree(JSONObject obj, String product, boolean en, boolean onlyItem) {
        //构建返回结果
        List<JSONTreeNode> array = new ArrayList<>();

        //根节点ID,默认为ROOT
        String rootId = obj.getString("rootId");
        if (StringUtil.isEmpty(rootId)) {
            rootId = ConstantVars.TREE_ROOT;
        }

        //字典编码
        String ddCode = obj.getString("ddCode");
        //字典名称，非必需字段
        String ddName = obj.getString("ddName");
        //字典标识，非必需字段 创建根节点对象ID使用,一次加载多个字典时使用
        /**
         * 当加载多个字典时，该字段用于表示字典绑定字段的编码
         */
        String nodeInfo = obj.getString("nodeInfo");

        //构建根节点
        JSONTreeNode emptyRoot = new JSONTreeNode();
        emptyRoot.setText(ddName);
        emptyRoot.setParent("ROOT");
        emptyRoot.setId("ROOT_" + nodeInfo);
        emptyRoot.setNodeInfo(nodeInfo);

        //查找字典主表记录
        DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
        if (dictionary == null) {
            dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode));
            if (dictionary == null) {
                throw new PlatformException("未找到数据字典：" + ddCode + "!", PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR, new Object[]{ddCode});
            }
        }

        //字典类型
        String ddType = dictionary.getStr("DICTIONARY_DDTYPE");
        if (!DDType.CUSTOM.equals(ddType)) {
            throw new PlatformException("错误的字典类型：" + ddType + "!", PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR, new Object[]{ddCode});
        }

        //前端sql条件转换
        Query query;
        if (StringUtils.isNotBlank(obj.getString("j_query"))) {
            query = Query.build(obj.getString("j_query"));
        } else {
            query = new Query();
        }

        List<Condition> customQuery = (List<Condition>) obj.get("customQuery");
        query.addCustoms(JSONArray.toJSONString(customQuery));

        // 无 ddWhereSql ddOrderSql
        String beanName = dictionary.getStr("DICTIONARY_CLASS");
        String beanMethod = dictionary.getStr("DICTIONARY_METHOD");
        HashMap<String, String> params = new HashMap();
        if (obj.containsKey("params")) {
            JSONObject varObj = obj.getJSONObject("params");
            for (String key : varObj.keySet()) {
                params.put(key, varObj.getString(key));
            }
        }
        DicInfoVo dicInfoVo = new DicInfoVo();
        dicInfoVo.setParams(params);
        dicInfoVo.setRootId(rootId);
        dicInfoVo.setDdCode(ddCode);
        dicInfoVo.setFieldName(ddName);
        dicInfoVo.setFieldCode(nodeInfo);
        dicInfoVo.setCustomerVariables(getCustomerVariables(obj));
        if (StringUtil.isNotEmpty(nodeInfo)) {
            dicInfoVo.setIdSuffix("_" + nodeInfo);
        }
        if (!query.getOrder().isEmpty()) {
            dicInfoVo.setOrderSql(JSONObject.toJSONString(query.getOrder()));
        }
        if (!query.getCustom().isEmpty()) {
            dicInfoVo.setWhereSql(JSONObject.toJSONString(query.getCustom()));
        }
        dicInfoVo.setConditions(query.getCustom());
        JSONTreeNode rootNode = invokeRemoteService(product, ddCode, beanName, beanMethod, dicInfoVo);
        rootNode.setText(ddName);
        if (onlyItem) {
            array.addAll(rootNode.getChildren());
        } else {
            array.add(rootNode);
        }
        return array;
    }

    @Override
    public List<JSONTreeNode> loadLinkTree(String ddCode, String parentId, String parentCode, String rootId, String paramStr, boolean en, Query query) {
        if (StringUtil.isEmpty(rootId)) {
            rootId = ConstantVars.TREE_ROOT;
        }
        List<JSONTreeNode> array = new ArrayList<>();
        //查询字典主表信息
        DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
        if (dictionary == null) {
            dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode));
        }
        if (dictionary == null) {
            throw new PlatformException("未找到数据字典：" + ddCode + "!", PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR);
        }

        //产品类型编码
        String productCode = dictionary.getStr("SY_PRODUCT_CODE");

        //自定义后端
        // 无 ddWhereSql ddOrderSql
        String beanName = dictionary.getStr("DICTIONARY_CLASS");
        String beanMethod = dictionary.getStr("DICTIONARY_METHOD");
        HashMap<String, String> params = new HashMap();
        if (StringUtil.isNotEmpty(paramStr)) {
            JSONObject varObj = JSON.parseObject(paramStr);
            for (String key : varObj.keySet()) {
                params.put(key, varObj.getString(key));
            }
        }
        DicInfoVo dicInfoVo = new DicInfoVo();
        dicInfoVo.setParams(params);
        dicInfoVo.setRootId(rootId);
        dicInfoVo.setDdCode(ddCode);
        //不同
        dicInfoVo.setParentId(parentId);
        dicInfoVo.setParentCode(parentCode);
        if (!query.getOrder().isEmpty()) {
            dicInfoVo.setOrderSql(JSONObject.toJSONString(query.getOrder()));
        }
        if (!query.getCustom().isEmpty()) {
            dicInfoVo.setWhereSql(JSONObject.toJSONString(query.getCustom()));
        }
        dicInfoVo.setConditions(query.getCustom());
        Object bean = SpringContextHolder.getBean(beanName);
        JSONTreeNode rootNode = invokeRemoteService(productCode, ddCode, beanName, beanMethod, dicInfoVo);
        //不同
        array.addAll(rootNode.getChildren());
        return array;
    }

    private JSONTreeNode invokeRemoteService(String product, String ddCode, String beanName, String method, DicInfoVo dicInfoVo) {
        CustomBeanInvokeRpcService customBeanInvokeRpcService;
        if(PRODUCT_CORE_META.equals(product)){
            customBeanInvokeRpcService = SpringContextHolder.getBean(CustomBeanInvokeRpcService.class);
        }else{
            customBeanInvokeRpcService = RpcSchemaFactory.getRemoteProvierClazz(product,"customBeanInvokeRpcService",CustomBeanInvokeRpcService.class);
        }
        return customBeanInvokeRpcService.invoke(beanName,method,dicInfoVo);
    }

}
